/**
 * 常用JS变量:
 * agentEvent = 代理模式下自动点击模块
 * acEvent= 无障碍模式下自动点击模块
 * device = 设备信息模块
 * file = 文件处理模块
 * http = HTTP网络请求模块
 * shell = shell命令模块
 * thread= 多线程模块
 * image = 图色查找模块
 * utils= 工具类模块
 * global = 全局快捷方式模块
 * 常用java变量：
 *  context : Android的Context对象
 *  javaLoader : java的类加载器对象
 * 导入Java类或者包：
 *  importClass(类名) = 导入java类
 *      例如: importClass(java.io.File) 导入java的 File 类
 *  importPackage(包名) =导入java包名下的所有类
 *      例如: importPackage(java.util) 导入java.util下的类
 *
 */
importClass(java.io.File);
importClass(android.content.Intent);
importClass(android.net.Uri);
importClass(android.os.Build);
importClass(android.os.StrictMode);
importClass(android.widget.TextView);
importClass(android.provider.Settings);
const xhs_data_path = "/sdcard/Pictures/xhs_ec_config/flushData/data.txt";
const xhs_datafolder = "/sdcard/Pictures/xhs_ec_config/flushData/";
const logPath = "/sdcard/Pictures/xhs_ec_config/flushData/log/";
const xhs_nodeInfo_path = "/sdcard/Pictures/xhs_ec_config/flushData/nodeData/nodeInfo.json";
const xhs_nodeInfo_temp = "/sdcard/xhs_ec_config/flushData/nodeData/nodeInfo.json";
const xhs_collect_path = "/sdcard/Pictures/xhs_ec_config/flushData/jumplink.txt";
const temp_path = "/sdcard/xhs_ec_config/flushData/";
let keywordSet = new Set();
let xhsIdSet = new Set();
let nickNameSet = new Set();
let keyWordMap = new Map();
let idSearchMap = new Map();
const xhsAppPkgName = "com.xingin.xhs";
let treeRoot = {
    "keyWord": [],//
    "idSearch": [],//
    "jump": []
}
let xhsTask = {
    xhs_id: "",//小红书号，唯一
    taskType: "",//任务类型，关键字，跳转，id搜索，关键字+id搜索
    title: "",//笔记标题
    keyword: "",//关键字数组
    username: "",
    url: "",
    dianZan: 0,
    shouCang: 0,
    guanZhu: 0,
}
const columns = ["taskType", "keyword", "xhs_id", "name", "title", "text"];
let UIData = {
    "taskNumber": 0,
    "startTime": 1,
    "endTime": 3,
    "splideTimes": 20,
    "airMode": "",
    "startTime_splide": 1,
    "endTime_splide": 3,
}
let map = {
    "xhs_id": "",
    "taskType": "",
    "title": "",
    "keyword": "",
    "username": "",
    "url": "",
    "dianZan": 0,
    "shouCang": 0,
    "guanZhu": 0,
    "append_taskType": "",//追加任务，关键字+id搜索,
    "append_xhsId": "",//追加的小红书id
};
//节点信息
let enumId = {};

//7.28版本控件id


/**
 * 打开小红书
 */
function openXHS() {
    utils.openApp(xhsAppPkgName);
}


/**
 * 匹配标题并且点击
 * @param data
 * @param viewId
 * @returns {boolean}
 */
function mateTitleAndClick(data, viewId) {
    let titleArray = [];
    let addTitleMap = new Map();
    let backupData = new Map();
    for (let i = 0; i < data.length; i++) {
        let title = data[i].split("----")[2]
        titleArray.push(title);
        backupData.set(title, data[i]);
        if (data[i].toString().indexOf("id搜索") > -1) {
            addTitleMap.set(title, data[i]);
        }
    }
    logd(titleArray);
    let searchResult_viewId = id(viewId);
    let centX = rSwipe.getNodeCenterX(searchResult_viewId);
    let height = rSwipe.getNodeHeight(searchResult_viewId);
    let startY = height - height / 8;
    let endY = height / 8;
    logd("titleArray= " + titleArray);
    // logd("centY =" +centY);
    let title = null;
    let titleSet = new Set(titleArray);
    let maxSize = UIData.splideTimes;
    for (let i = 0; i < maxSize; i++) {
        titleSet.forEach(function (e1, e2) {
            title = e1;
            logd("当前匹配title===>" + title);
            let textList = textMatch("^" + title + ".*").clickable(false).getOneNodeInfo(200);
            if (textList == null) {
                logd("当前页面不在搜索结果页面");
                return;
            }
            logd(JSON.stringify(textList));
            let tempTitle = textList.text;
            logd("tempTitle====>" + tempTitle);
            if (Trim(tempTitle).indexOf(Trim(title)) > -1) {
                logd("匹配成功");
                logd("笔记标题匹配成功");
                let node = textList.parent();
                // logd(JSON.stringify(node));
                for (let k = 0; k < 3; k++) {
                    let x = 0.5 * (node.bounds.left + node.bounds.right);
                    let y = 0.5 * (node.bounds.top + node.bounds.bottom);
                    logw("x:" + x + ",y:" + y);
                    doubleClickPoint(x, y);
                    sleep(1000);
                    let searchResult_viewId = id(viewId);
                    if (!has(searchResult_viewId)) {
                        break;
                    }
                }
                titleSet.delete(title);
                deleteStrInFile(backupData.get(title), (temp_path + "data.txt"));
                sleep(2000);
                let isVideoNote = checkNoteType();
                if (!isVideoNote) {
                    logd("当前为图文笔记");
                    if (addTitleMap.has(title)) {
                        let userIcon = id(enumId.picwordNote_nickName).getOneNodeInfo(1000);
                        sleep(2000);
                        logd(JSON.stringify(userIcon));
                        if (userIcon == null) {
                            for (let j = 0; j < 3; j++) {
                                let x = 550;
                                let y = 150;
                                doubleClickPoint(x,y);
                                sleep(1000);
                                if (checkUserPage()) {
                                    break;
                                }
                            }
                        }else {
                            let x = 0.5 * (userIcon.bounds.left + userIcon.bounds.right);
                            let y = 0.5 * (userIcon.bounds.top + userIcon.bounds.bottom);
                            logd(x + ":" + y);
                            doubleClickPoint(x, y);
                        }
                        sleep(500);
                        let link = addTitleMap.get(title);
                        link = link.substring(link.indexOf("id搜索"), link.length);
                        logd(link);
                        let list = [link];
                        mateUserPageTitleAndClick(list, UIData.splideTimes);
                    } else {
                        browseNote();
                        randomSleep(UIData.startTime, UIData.endTime);
                        doDianZan_Picword();
                        randomSleep(UIData.startTime, UIData.endTime);
                        if (checkScore()) {
                            doXhsScore();
                            randomSleep(UIData.startTime, UIData.endTime);
                        }
                        doShouCang_Picword();
                        randomSleep(UIData.startTime, UIData.endTime);
                        randomSleep(UIData.startTime, UIData.endTime);
                        picwordBack();
                    }
                } else  {
                    if (addTitleMap.has(title)) {
                        let userIcon = id(enumId.videoNote_nickName).getOneNodeInfo(1000);
                        if (userIcon == null) {
                            for (let j = 0; j < 3; j++) {
                                doubleClickPoint(238,1439);
                                sleep(1000);
                                if (checkUserPage()) {
                                    break;
                                }
                            }
                        }else {
                            let x = 0.5 * (userIcon.bounds.left + userIcon.bounds.right);
                            let y = 0.5 * (userIcon.bounds.top + userIcon.bounds.bottom);
                            logd(x + ":" + y);
                            clickPoint(x, y);
                        }

                        sleep(500);
                        let link = addTitleMap.get(title);
                        link = link.substring(link.indexOf("id搜索"), link.length);
                        logd(link);
                        let list = [link];
                        mateUserPageTitleAndClick(list, UIData.splideTimes);
                    } else {
                        doDianZan_video();
                        randomSleep(UIData.startTime, UIData.endTime);
                        if (checkScore()) {
                            doXhsScore();
                            randomSleep(UIData.startTime, UIData.endTime);
                        }
                        doShouCang_video();
                        randomSleep(UIData.startTime, UIData.endTime);
                        videoBack();
                    }
                }
            }
            sleep(1000);
            if (titleSet.size == 0) {
                maxSize = random(i, i + 4);
                logd("maxSize:" + maxSize);
            }
        })

        logd("第" + (i + 1) + "次翻页");
        rSwipe.rndSwipe(centX, startY, centX, endY, 50, 100, 120);
        randomSleep(UIData.startTime_splide, UIData.endTime_splide);
    }
    return true;
}



/**
 * 初始化笔记路径
 */
function getSchemaArray(note_jumpLink_path) {
    let urls = file.readAllLines(note_jumpLink_path);
    if (urls == null) {
        toast("笔记链接为空");
        return null;
    }
    urls = urls.toString().split(",");
    let array = [];
    for (let i = 0; i < urls.length; i++) {
        let url = urls[i].toString();
        url = url.match("item/[0-9][a-zA-Z0-9]{0,24}");
        url = url.toString().split("/");
        logd("url=" + url);
        let temp = "xhsdiscover://item/" + url[1];
        array.push(temp)
    }
    return array;
}


/**
 * 当前页面是否用户笔记页面
 */
function checkUserPage() {
    let currentPage = id(enumId.user_page_noteViewId);
    return has(currentPage);
}


/**
 *
 * @param titles 同一个用户下的笔记标题数组
 * @param splidetimes 下滑次数
 */
function mateUserPageTitleAndClick(list, splidetimes) {
    let titleSet = new Set();
    let titleMap = new Map();
    let errMsg = null;
    for (let i = 0; i < list.length; i++) {
        let title = list[i].split("----")[3];
        errMsg = list[i];
        titleSet.add(title);
        titleMap.set(title, list[i]);
    }
    logd(splidetimes);
    let size = 60;
    let tempArray = [];
    rSwipe.rndSwipe(500, 800, 520, 20, 80, 80, 80);
    for (let j = 0; j < size; j++) {
        let noteView = id(enumId.user_page_noteViewId).getOneNodeInfo(1000);
        sleep(1000);

        if (noteView == null) {
            toast("笔记数组为空");
            if (!checkUserPage()) {
                logd("当前不在用户笔记页");
            }
            continue
        }
        let notes = noteView.allChildren();
        logd(notes.length);
        for (let i = 0; i < notes.length; i++) {
            let n = notes[i];
            sleep(1000);
            if (n.clz == "android.widget.LinearLayout") {
                logd("不是笔记");
                continue
            }
            if (n.clz == "android.widget.FrameLayout") {
                let isVideoNote = null;
                let title = "";
                if (titleSet.size == 0) {
                    break;
                }
                while (true) {
                    // n.click();
                    let x = 0.5 * (n.bounds.left + n.bounds.right);
                    let y = 0.5 * (n.bounds.top + n.bounds.bottom);
                    clickPoint(x, y);
                    sleep(1000);
                    isVideoNote = checkNoteType();
                    logd("是否视频笔记:" + isVideoNote);
                    sleep(500);
                    if (isVideoNote) {
                        let videoTitle = id(enumId.videoNote_title).getOneNodeInfo(1000);
                        logd("笔记标题："+videoTitle);
                        if (videoTitle != null) {
                            title = videoTitle.text;
                            title = title != null ? title.toString() : title;
                            break;
                        }
                    } else {
                        picword_splide("DOWN");//适配手机默认下滑才能读取标题
                        sleep(2000);
                        let picTitle = id(enumId.picwordNote_title).getOneNodeInfo(1000);
                        logd("笔记标题："+picTitle);
                        if (picTitle != null) {
                            logd(JSON.stringify(picTitle));
                            title = picTitle.text;
                            title = title != null ? title.toString() : title;
                            break;
                        } else {
                            logd("当前笔记没有标题！！！");
                            let contentText = id(enumId.picwordNote_content);
                            if (has(contentText)) {
                                title = getNodeAttrs(contentText, "text");
                                break;
                            } else {
                                break;
                            }

                        }
                    }
                }
                if (title == null || title == "") {
                    break;
                }

                logd("当前笔记标题:" + title);

                titleSet.forEach(function (v1, v2) {
                    // randomSleep(UIData.startTime,UIData.endTime);
                    // sleep(500);
                    logd("匹配目标笔记:" + v1);
                    if (title == null) {
                        return;
                    }
                    if (checkUserPage()) {
                        logw(1);
                        return;
                    }

                    if (title.toString().indexOf(v1) > -1) {
                        logd("找到笔记");
                        titleSet.delete(v1);
                        deleteStrInFile(titleMap.get(v1), (temp_path + "data.txt"));
                        logd("当前任务笔记数量:" + titleSet.size);
                        if (isVideoNote) {
                            doDianZan_video();
                            randomSleep(UIData.startTime, UIData.endTime);
                            if (checkScore()) {
                                doXhsScore();
                                randomSleep(UIData.startTime, UIData.endTime);
                            }
                            doShouCang_video();
                            randomSleep(UIData.startTime, UIData.endTime);
                        } else {
                            browseNote();
                            randomSleep(UIData.startTime, UIData.endTime);
                            doDianZan_Picword();
                            randomSleep(UIData.startTime, UIData.endTime);
                            if (checkScore()) {
                                doXhsScore();
                                randomSleep(UIData.startTime, UIData.endTime);
                            }
                            doShouCang_Picword();
                            randomSleep(UIData.startTime, UIData.endTime);
                        }
                    }
                })
                if (isVideoNote) {
                    videoBackPoint();
                } else {
                    picwordBackPonit();
                }

            }
            if (titleSet.size == 0) {
                logd("笔记匹配完成！！！");
                size = j + random(1, 3);
                break;
            }

        }
        if (j == 59) {
            loge("找不到这条笔记："+list[0]);
        }
        logw("滑动第" + (j + 1) + "页");
        splideNode(enumId.user_page_noteViewId, true, 1);
    }
}

/**
 *  计算数组中重复元素
 * @param array
 * @param element
 * @constructor
 */
function calculationArray(array, element) {
    if (array == null) {
        logd("数组不可为空");
        return 0;
    }
    if (element == null) {
        logd("笔记元素为null");
        return 0;
    }
    let sum = 0;
    for (let i = 0; i < array.length; i++) {
        if (array[i] == element) {
            sum++;
        }
    }
    return sum;
}


/**
 * 随机停止时间
 * @param start 单位秒
 * @param end 单位秒
 */
function randomSleep(start, end) {
    sleep(random(start, end) * 1000);
}

/**
 * 处理小红书评分
 */
function checkScore() {
    let node = textMatch("^您对小红书的评分如何?.*");
    return has(node);
}

/**
 * 初始化节点信息
 * @param xhs_nodeInfo_path
 * @returns {boolean}
 */
function initXHSNodeInfo(xhs_nodeInfo_path) {
    logd("开始初始化小红书节点信息");
    logd('应用版本号：' + utils.getAppVersionName(xhsAppPkgName));
    let ret = file.readFile(xhs_nodeInfo_temp);
    enumId = JSON.parse(ret);
    return enumId != null ? true : false;
}
// initPopUpWindow();
/**
 * 异步处理弹窗
 */
function initPopUpWindow() {
    let t1 = setInterval(function (){
        let newestVersion = textMatch("^最新版本发布").getOneNodeInfo(1000);
        if (newestVersion!=null) {
            clickPoint(200,200);
        }
        let wifiText = textMatch("^当前处于非 WiFi 环境.*");
        if (has(wifiText)) {
            clickText("知道了");
        }
    },3000);

}


main();

function picword_splide(direct) {
    let noteId = id(enumId.picwordNode_noteContent).getOneNodeInfo(1000);
    if (direct=="DOWN") {
        logd("笔记下滑");
        if (noteId == null) {
                let width = device.getScreenWidth();
                let height = device.getScreenHeight();
                let x = 0.5*width;
                let y = 0.85*height;
                rSwipe.rndSwipe(x, y, x, (0.1*random(1,4) * y), 80, 80, 100);
                  sleep(500);
        }else {
            let x = 0.5 * (noteId.bounds.left + noteId.bounds.right);
            let y = rSwipe.getNodeHeight(id(enumId.picwordNode_noteContent)) - 100;
            rSwipe.rndSwipe(x, y, x, (0.1*random(1,4) * y), 80, 80, 100);
            sleep(500);
        }

    }else {
        logd("笔记上滑");

        let x = 0.5 * (noteId.bounds.left + noteId.bounds.right);
        logd(x);
        let y = rSwipe.getNodeHeight(id(enumId.picwordNode_noteContent));
        logd(y);
        rSwipe.rndSwipe(x, 0.3*y, x,  y, 80, 80, 100);
        sleep(1000);
        rSwipe.rndSwipe(x, 0.3*y, x,  y, 80, 80, 100);
        sleep(1000);
    }

}

function main() {

    setLogFixedViewEx();
    if (!file.exists(logPath)) {
        file.mkdirs(logPath)
    }
    let logName = device.getModel()+"_"+time();
    let s = setSaveLogEx(true, logPath, 1024 * 1024,logName);
    logd("日志保持路径:" + logPath);

    let buttonType = ui.getConfig("buttonType");
    logd(buttonType);
    if (buttonType == "重置") {
        logw("开始重置");
        let fileName = temp_path + "data.txt";
        let t1 = file.copy(xhs_data_path, fileName);
        logw("重置笔记数据：" + t1);
        let t2 = file.copy(xhs_nodeInfo_path, xhs_nodeInfo_temp);
        logw("重置节点数据:" + t2);
        if (file.exists(temp_path)) {
            sleep(500);
            deleteConfig("buttonType");
            toast("重置数据成功");
            exit();
        }
    }
    //如果自动化服务正常
    if (!autoServiceStart(3)) {
        logd("自动化服务启动失败，无法执行脚本")
        exit();
        return;
    }
    let result = daemonEnv(true);
    logd("激活守护:" + result);
    let airMode = ui.getShareData("airMode");
    logd("airMode=" + airMode);
    let taskNumber = ui.getShareData("taskNumber");
    logd("taskNumber=" + taskNumber);
    let startTime = ui.getShareData("startTime")
    logd("startTime=" + startTime);
    let endTime = ui.getShareData("endTime")
    logd("endTime=" + endTime);
    let startTime_splide = ui.getShareData("startTime_splide")
    logd("startTime_splide=" + startTime_splide);
    let endTime_splide = ui.getShareData("endTime_splide")
    logd("endTime_splide=" + endTime_splide);
    let splideTimes = ui.getShareData("splideTimes");
    logd("splideTimes=" + splideTimes);
    UIData.airMode = airMode || 4;
    UIData.taskNumber = taskNumber || 5;
    UIData.startTime = startTime || 1;
    UIData.endTime = endTime || 3;
    UIData.splideTimes = splideTimes || 20;
    UIData.startTime_splide = startTime_splide || 1;
    UIData.endTime_splide = endTime_splide || 3;
    // logw(JSON.stringify(UIData));
    //开始再这里编写代码了！！
    toast("脚本开始启动");
    initXHSNodeInfo(xhs_nodeInfo_temp)
    sleep(2000);
    logw("节点初始化成功：" + JSON.stringify(enumId));
    logd("打开小红书");
    launch(xhsAppPkgName);

    initPopUpWindow();

    initConfig();

    logd("开始任务类型选择....");
    sleep(2000);
    randomSleep(1, 3);
    if (!isXHSHome()) {
        backHome();
    }
    let taskTypes = ["跳转", "关键词", "id搜索"];
    for (let i = 0; i < taskTypes.length; i++) {
        let v = taskTypes[i];
        if (v == "跳转") {
            doJumpTask();
        } else if (v == "关键词") {
            randomSleep(UIData.startTime, UIData.endTime);
            taskKeywordSearch();
        } else if (v == "id搜索") {
            randomSleep(UIData.startTime, UIData.endTime);
            taskXhsIdSearch();
        }
    }
}


/**
 * 检查笔记是否已点赞
 * @returns {字符串数组|Rect对象数组|null}
 */
function checkDianzan_picword() {
    return getNodeAttrs(id(enumId.picwordNote_dianzan), "selected");
}

/**
 * 检查笔记是否已点赞
 * @returns {字符串数组|Rect对象数组|null}
 */
function checkDianzan_video() {
    return getNodeAttrs(id(enumId.videoNote_dianzan), "selected");
}


/**
 * 检查笔记是否已收藏
 * @returns {字符串数组|Rect对象数组|null}
 */
function checkShoucang_picword() {
    return getNodeAttrs(id(enumId.picwordNote_shoucang), "selected");
}

/**
 * 检查笔记是否已收藏
 * @returns {字符串数组|Rect对象数组|null}
 */
function checkShoucang_video() {
    return getNodeAttrs(id(enumId.videoNote_shoucang_icon), "selected");
}

/**
 * 判断用户主页笔记是否视频笔记，true为视频笔记，false为图文笔记
 */
function checkNoteType() {
    let v1 = waitExistNode(id(enumId.videoNote_userIcon),1000);
    let v2 = waitExistNode(id(enumId.videoNote_back),1000);
    return v1 || v2;
}


/**
 * 给出最外层的节点id,水平方向，上下，
 * @param node
 * @param times 胡奥东次数
 */
function splideNode(nodeId, isSplide, times) {
    // logw(nodeId);
    if (!checkUserPage()) {
        logd("当前不在滑动页");
        return false;
        // backs(1,1000);
    }

    let searchResult_viewId = id(nodeId);
    let width = rSwipe.getNodeWidth(searchResult_viewId);
    let height = rSwipe.getNodeHeight(searchResult_viewId);
    let startX, startY, endX, endY;
    startY = random(8,9)*0.1*height;
    endY = random(1,3)*0.1*height;
    startX = (width / 4) * 3;
    endX = startX;
    if (isSplide) {
        rSwipe.rndSwipe(startX, startY, endX, endY, 80, 80, 80);
        randomSleep(UIData.startTime_splide, UIData.endTime_splide);
    }

}


/**
 * 给小红书打拼分
 */
function doXhsScore() {
    let node = textMatch("^您对小红书的评分如何?.*").getOneNodeInfo(500);
    logd("出现小红书评分框："+node);
    let parent = node.parent();
    logd(JSON.stringify(parent));
    let startView = parent.child(1);
    logd(JSON.stringify(startView));
    let childNode = startView.child(3);
    childNode.click();
}


/**
 * 判断是否在登录状态
 * @returns {bool|布尔型}
 */
function isXHSHome() {
    let fabuBut = id(enumId.mainPage_fabuBut);
    let shouYeBug = text("首页");
    sleep(1000);
    clickText("首页");
    sleep(1000);
    return has(fabuBut) && has(shouYeBug);
}


/**
 * 进入关键字搜索
 * @param keywords
 * @param searchType
 * @returns {boolean}
 */
function search(keywords) {
    // logd("回到首页发现："+URL_intent(home_url));
    if (!isXHSHome()) {
        backSearchInput();
    }
    logd("进入关键字搜索 .....");
    sleep(2000);
    let searchicon = id(enumId.mainPage_searchIconId);
    while (true) {
        let result = click(searchicon);
        sleep(500);
        let searchInput = id(enumId.search_inputId);
        if (has(searchInput)) {
            break;
        }
    }
    randomSleep(1, 3);
    //进入搜索狂
    logd("进入搜索栏......");
    let searchInput = id(enumId.search_inputId);
    let rs = waitExistNode(searchInput, 2000);
    if (rs) {
        logd("输入关键字:" + keywords);
        let node = searchInput.getOneNodeInfo(2000);
        // let rs1 = node.inputText(keywords);
        doInputText(node, keywords);
        sleep(2000);
        logd("点击搜索");
        let search = id(enumId.search_page_searchBut);
        while (true){
            let rs2 = click(search);
            logd(rs2 ? "搜索成功" : "搜索失败");
            sleep(2000);
            if (checkSearchPage()) {
                break;
            }
        }
        return true;
    }
    return true;
}

/**
 * 根据小红书id查找用户
 * @param xhsId
 * @param xhsName
 */
function searchByXhsId(nickName) {
    if (!isXHSHome()) {
        backSearchInput();
    }
    randomSleep(1, 3);
    logd("进入用户ID搜索 .....");
    randomSleep(1, 3);

    let searchIcon = id(enumId.mainPage_searchIconId);
    while (true) {
        let result = click(searchIcon);
        randomSleep(1, 3);
        let searchInput = id(enumId.search_inputId);
        if (has(searchInput)) {
            break;
        }
    }
    randomSleep(1, 3);
    //进入搜索狂
    logd("进入搜索栏......");
    let searchInput = id(enumId.search_inputId);
    if (has(searchInput)) {
        logd("输入昵称:" + nickName);
        let node = searchInput.getOneNodeInfo(2000);
        // node.inputText(xhsId);
        doInputText(node, nickName);
        sleep(2000);
        logd("点击搜索");
        let search = id(enumId.search_page_searchBut).getOneNodeInfo(1000);
        while (true) {
            search.click();
            randomSleep(1, 3);
            if (checkSearchPage()) {
                break;
            }
        }
        randomSleep(1, 3);
        while (true) {
            clickText("用户");
            randomSleep(1, 3);
            let userIcon = id(enumId.searchPage_userNickName);
            if (has(userIcon)) {
                break;
            }
        }
        randomSleep(1, 3);
        let noteArray = id(enumId.search_page_noteViewId).getOneNodeInfo(1000);
        if (noteArray == null) {
            logd("用户搜索为空，返回上一步");
            return false;
        }
        let temp = idSearchMap.get(nickName);
        let xhsId = temp[0].split("----")[1];
        logd(xhsId);
        let tempText = "小红书号：" + xhsId;
        let nodeView = id(enumId.search_page_noteViewId);
        let sX = rSwipe.getNodeCenterX(nodeView);
        let sY = rSwipe.getNodeHeight(nodeView) - 200;
        let eX = sX;
        let eY = rSwipe.getNodeCenterY(nodeView) - 300;
        while (true) {
            let textNode = textMatch("^" + tempText + ".*").getOneNodeInfo(2000);
            if (textNode == null) {
                rSwipe.rndSwipe(sX, sY, eX, eY, 50, 50, 80);
                sleep(random(1000, 1500));
                continue
            }
            textNode.click();
            randomSleep(1, 3);
            let userPage = id(enumId.user_page_noteViewId);
            if (has(userPage)) {
                break;
            }
            sleep(1000);
        }
        return true;
    }
}

/**
 * 当前页面是否在搜索结果页面
 */
function checkSearchPage(){
    let quanbu = text("全部");
    let yonghu = text("用户");
    return has(quanbu) && has(yonghu);
}


// taskXhsIdSearch();
/**
 * 根據小红书id和名字搜索精准用户
 */
function taskXhsIdSearch() {
    nickNameSet.forEach(function (s1, s2) {
        logd("小红书nickName:" + s1);
        searchByXhsId(s1);
        randomSleep(UIData.startTime, UIData.endTime);
        let list = idSearchMap.get(s1);
        mateUserPageTitleAndClick(list, UIData.splideTimes);
        randomSleep(UIData.startTime, UIData.endTime);
    })
}




/**
 *
 * @param keyword
 * @param titleArray
 */
function taskKeywordSearch() {
    if (keywordSet.size == 0) {
        logd("关键字任务为空");
        return false;
    }
    logd("开始关键字笔记任务....");
    let keywordArray = Array.from(keywordSet);
    logd("所有关键字：" + keywordArray);
    for (let m = 0; m < keywordArray.length; m++) {
        let key = keywordArray[m];//从数组取出第一个关键字
        logd("key=" + key);
        let data = keyWordMap.get(key);
        logd("data=" + data);
        search(key);
        clickText("全部");
        randomSleep(1, 3);
        //判断是否需要追加搜索
        randomSleep(1, 3);
        if (data.length >= 1) {
            let temp = JSON.stringify(data[0]).toString();
            let searchType = "综合";
            if (temp.indexOf("最新") > -1) {
                searchType = "最新";
                click(id(enumId.searchPage_newest));
            } else if (temp.indexOf("最热") > -1) {
                searchType = "最热";
                click(id(enumId.searchPage_hotest));
            }
            sleep(2000);
            logd("searchType:" + searchType);

            let rs = mateTitleAndClick(data, enumId.search_page_noteViewId);
            sleep(1000);
            logd("开始匹配下一个关键字");
            backSearchInput();
            randomSleep(2, 5);
        }
    }
    return true;
}


/**
 * 回到小红书首页
 */
function backHome() {
    for (let i = 0; i < 9; i++) {
        let node = id(enumId.mainPage_fabuBut);
        if (node != null) {
            break;
        }
        backs(1, 1000);
    }
}

/**
 * 回到搜索框页
 */
function backSearchInput() {
    for (let i = 0; i < 9; i++) {
        let searchInput = id(enumId.search_inputId);
        sleep(500);
        if (has(searchInput)) {
            break;
        }
        back();
        randomSleep(1, 3);
    }
}

/**
 * 模拟真人输入文本
 * @param content
 */
function doInputText(node, content) {
    if (content == null || content == "") {
        logd("输入内容不可为空");
        return false;
    }
    if (node == null) {
        logd("节点不存在");
        return false;
    }
    if (content.length > 2) {
        let chars = content.split("");
        let temp = "";
        for (let i = 0; i < chars.length; i++) {
            temp += chars[i];
            node.inputText(temp);
            sleep(300);
        }
    } else {
        node.inputText(content);
    }

}

// testMain();

/**
 * 浏览图文笔记
 */
function browseNote() {
    // enumId.picwordNode_noteContent = "com.xingin.xhs:id/noteContentLayout";
    // enumId.picwordNote_pageNum = "com.xingin.xhs:id/b20";
    logd("进入图文笔记浏览...");
    picword_splide("UP");//进入浏览滑动到上面
    let noteParent = id(enumId.picwordNode_noteContent).getOneNodeInfo(1000);
    sleep(1000);
    let pic = id(enumId.picwordNode_noteContent);
        let sx = rSwipe.getNodeCenterX(pic);
        let sy = rSwipe.getNodeCenterY(pic);
        let width = rSwipe.getNodeWidth(pic);
        let pageNum = null;
        while (true) {
            rSwipe.rndSwipe(width - 100, sy, 0.5 * sx, sy, 80, 80, 80);
            let pageNode = id(enumId.picwordNote_pageNum);
            sleep(500);
            if (has(pageNode)) {
                pageNum = pageNode.getOneNodeInfo(1000);
                logd(pageNum);
                if (pageNum == null) {
                    break;
                }
                sleep(1500);
                pageNum = pageNum.text;
                logd("左滑页数："+pageNum);
                let num0 = pageNum.split("/")[0];
                logd("num0="+num0);
                let num1 = pageNum.split("/")[1];
                logd("num1="+num1);
                if (num0 == num1) {
                    break
                }
            }else {
                break
            }
        }
        randomSleep(1, 3);
        //向下滑动浏览
        for (let i = 0; i < random(1, 4); i++) {
            rSwipe.rndSwipe(sx, 1.5 * sy, sx, 0.5 * sy, 50, 50, 100);
            randomSleep(UIData.startTime_splide, UIData.endTime_splide);
        }
}


// testMain()
function initConfig() {
    logd("开始初始化配置文件...");
    let content = file.readAllLines((temp_path + "data.txt"));
    logd(content);
    if (content == null) {
        toast("笔记链接为空");
        exit();
    }
    content = content.toString().split(",");
    for (let i = 0; i < content.length; i++) {
        let tempKeyword = "";
        let tempXhsId = "";
        let tempNickName = "";
        let temp = content[i].split("----");
        let tempType = temp[0];
        if (tempType == "关键词") {
            treeRoot.keyWord.push(content[i]);
            tempKeyword = temp[1];
            keywordSet.add(tempKeyword);
        }
        if (tempType == "id搜索") {
            treeRoot.idSearch.push(content[i]);
            tempNickName = temp[2];
            // xhsIdSet.add(tempXhsId);
            nickNameSet.add(tempNickName);
        }
        if (tempType == "跳转") {
            treeRoot.jump.push(content[i]);
        }
    }
    sleep(500);
    let keywordArray = treeRoot.keyWord;
    logd("keywordArray:" + keywordArray);
    logd("keywordSet:" + keywordSet.size);
    keywordSet.forEach(function (v, e) {
        logw("=====================================");
        logd("v:" + v);
        let t1 = [];
        for (let i = 0; i < keywordArray.length; i++) {
            let t = keywordArray[i].split("----");
            if (v.toString() == t[1].toString()) {
                logd("t[1]:" + t[1]);
                logd("key:" + v);
                t1.push(keywordArray[i]);
                keyWordMap.set(v, t1);
            }
        }
        logw("=====================================");
    });
    let xhsIdArray = treeRoot.idSearch;
    nickNameSet.forEach(function (v, e) {
        logw("=====================================");
        logd("v:" + v);
        let t1 = [];
        for (let i = 0; i < xhsIdArray.length; i++) {
            let t = xhsIdArray[i].split("----");
            if (v.toString() == t[2].toString()) {
                logd("昵称:" + v);
                logd("小红书号:" + t[1]);
                t1.push(xhsIdArray[i]);
                idSearchMap.set(v, t1);
            }
        }
        logw("=====================================");
    });
}

// testMain();

function testMain() {

    initXHSNodeInfo(xhs_nodeInfo_path);
    sleep(500);
    let tempText = "小红书号：705832603";
    let node = id("com.xingin.xhs:id/bux");
    let sX = rSwipe.getNodeCenterX(node) - 200;
    let sY = rSwipe.getNodeHeight(node);
    let eX = sX;
    let eY = rSwipe.getNodeCenterY(node) - 300;
    while (true) {
        let textNode = textMatch("^" + tempText + ".*").getOneNodeInfo(2000);
        logd(textNode);
        if (textNode == null) {
            rSwipe.rndSwipe(sX, sY, eX, eY, 50, 50, 50);
            sleep(random(1000, 1500));
            continue
        }
        textNode.click();
        randomSleep(1, 3);
        let userIcon = id(enumId.user_page_noteViewId);
        if (has(userIcon)) {
            break;
        }
        sleep(1000);
    }


}

/**
 * 在文本里面匹配字符串，然后删除返回true;
 * @param str
 * @param filePath
 */
function deleteStrInFile(str, filePath) {
    let temp = file.readFile(filePath);
    // logd(temp);
    if (temp == null) {
        toast("笔记链接为空");
        exit();
    }
    temp = temp.toString();
    temp = temp.replaceAll(str, "");
    // logd(temp);
    file.writeFile(temp, filePath);
    logd("删除成功");
}


/**
 * 判断图文笔记是否有页数
 */
function isExistPageNum() {

    let noteParent = id(enumId.picwordNode_noteContent).getOneNodeInfo(1000);
    sleep(1000);
    if (noteParent == null) {
        logd("12e");
        return true;
    }
    return noteParent.allChildren().length > 2 ? true : false;
}


/**
 * 初始化笔记路径
 */
function initNoteUrl(url) {

    if (url != null) {
        url = url.toString();
        url = url.match("item/[0-9][a-zA-Z0-9]{0,24}");
        url = url.toString().split("/");
        logd("url=" + url);
        return "xhsdiscover://item/" + url[1];
    }
    return null;
}

/**
 * 跳转任务
 */
function doJumpTask() {
    //查詢所有跳轉任務的鏈接
    // let noteUrl = "xhsdiscover://item/";
    let jumplinkSet = treeRoot.jump;
    if (jumplinkSet == null) {
        logd("没有跳转任务");
        return;
    }
    for (let i = 0; i < jumplinkSet.length; i++) {

        let temps = jumplinkSet[i].split("----");
        logd(temps);
        let noteUrl = initNoteUrl(temps[1]);
        logd("noteUrl:" + noteUrl);
        let rs = URL_intent(noteUrl);
        logd("跳转笔记链接成功：" + rs);
        sleep(2000);
        let isDianzan = jumplinkSet[i].indexOf("点赞") > -1 ? true : false;
        let isShoucang = jumplinkSet[i].indexOf("收藏") > -1 ? true : false;
        logd("判断当前笔记...");
        if (isPicwordNote()) {
            if (isDianzan) {
                doDianZan_Picword();
                randomSleep(UIData.startTime, UIData.endTime);
            }
            if (checkScore()) {
                doXhsScore();
                randomSleep(UIData.startTime, UIData.endTime);
            }
            if (isShoucang) {
                doShouCang_Picword();
                randomSleep(UIData.startTime, UIData.endTime);
            }
            deleteStrInFile(jumplinkSet[i], (temp_path + "data.txt"));
            picwordBack();
        } else {

            if (isDianzan) {
                doDianZan_video();
                randomSleep(UIData.startTime, UIData.endTime);
            }
            if (checkScore()) {
                doXhsScore();
                randomSleep(UIData.startTime, UIData.endTime);
            }
            if (isShoucang) {
                doShouCang_video();
                randomSleep(UIData.startTime, UIData.endTime);
            }
            deleteStrInFile(jumplinkSet[i], (temp_path + "data.txt"));
            videoBack();
        }
        sleep(4000);
    }
    ;

}

/**
 * app内跳转
 * @param url
 * @returns {*}
 * @constructor
 */
function URL_intent(url) {
    sleep(2000);
    var rt = utils.openActivity({
        "uri": url,
    });
    return rt;
}


/**
 * 图文笔记返回上一页
 */
function picwordBack() {
    // let backId = id(enumId.picwordNote_back).getOneNodeInfo(1000);
    // sleep(2000);
    // logd("返回成功:" + backId.click());
    backs(1, 1500);
}

/**
 * 图文笔记返回上一页
 */
function picwordBackPonit() {
    logw("图片笔记返回");
    let back = id(enumId.picwordNote_back).getOneNodeInfo(1000);
    if (back == null) {
        return false;
    }
    back.click();
    sleep(1000);
}


/**
 * 视频笔记返回上一页
 */
function videoBack() {
    logw("视频笔记返回");
    let back = id(enumId.videoNote_back).getOneNodeInfo(1000);
    if (back == null) {
        return false;
    }
    back.click();
    sleep(1000);

}

/**
 * 视频笔记返回上一页
 */
function videoBackPoint() {
    backs(1, 1500);
}


/**
 * 视频笔记点赞
 */
function doDianZan_video() {
    let dianzan = id(enumId.videoNote_dianzan);
    if (dianzan == null) {
        doXhsScore();
    }
    let x = rSwipe.getNodeCenterX(dianzan);
    let y = rSwipe.getNodeCenterY(dianzan);
    let r = clickPoint(x, y);
    logd("点赞完成");
}

/**
 * 图文笔记点赞
 */
function doDianZan_Picword() {
    let dianzan = id(enumId.picwordNote_dianzan);
    if (dianzan == null) {
        doXhsScore();
    }
    let x = rSwipe.getNodeCenterX(dianzan);
    let y = rSwipe.getNodeCenterY(dianzan);
    let r = clickPoint(x, y);
    sleep(500);
    logd("点赞成功");
}

/**
 * 视频笔收藏
 */
function doShouCang_video() {
    let shoucang = id(enumId.videoNote_shoucang);
    if (shoucang == null) {
        doXhsScore();
    }
    let x = rSwipe.getNodeCenterX(shoucang);
    let y = rSwipe.getNodeCenterY(shoucang);
    let r = clickPoint(x, y);
    logd("收藏成功:" + r);
}

/**
 * 图文笔收藏
 */
function doShouCang_Picword() {
    let shoucang = id(enumId.picwordNote_shoucang);
    if (shoucang == null) {
        doXhsScore();
    }
    let x = rSwipe.getNodeCenterX(shoucang);
    let y = rSwipe.getNodeCenterY(shoucang);
    let r = clickPoint(x, y);
    logd("收藏成功:" + r);
}

/**
 * 视频笔记返回true
 */
function isVideoNote() {
    let dianzanBut = id(enumId.videoNote_dianzan);
    let shouCnagBut = id(enumId.videoNote_shoucang);
    return has(dianzanBut) && has(shouCnagBut);
}

/**
 * 图文笔记返回true
 */
function isPicwordNote() {
    let dianzanBut = id(enumId.picwordNote_dianzan);
    let shouCnagBut = id(enumId.picwordNote_shoucang);
    return has(dianzanBut) && has(shouCnagBut);
}


/**
 * 字符串去除空格
 * @param str
 * @returns {*}
 * @constructor
 */
function Trim(str, is_global) {
    let result = str.replace(/(^\s+)|(\s+$)/g, "");
    is_global = is_global || "g";
    if (is_global.toLowerCase() == "g") {
        result = result.replace(/\s/g, "");
    }
    return result;
}


/**
 @description 通过包名启动应用。如果该包名对应的应用不存在，则返回false；否则返回true。
 @version     20201125
 @author      飞云<283054503@qq.com>
 @param       packageName {string} :应用包名
 @param       delay {number} :启动后等待时长，单位毫秒。默认5000
 @param       startNum {number} :重试次数。默认3
 @return      {boolean}:返回是否成功
 */
function launch(packageName, delay, startNum) {
    let result = false;
    if (!delay) {
        delay = 5000;
    }
    if (!startNum) {
        startNum = 3;
    }
    if (utils.isAppExist(packageName)) {
        if (getRunningPkg() === packageName) {
            logd('应用已经在前台');
            result = true;
        } else {
            logd('启动应用...');

            let selectors = text('允许');
            let num = 0;
            while (num < startNum) {
                if (getRunningPkg() === packageName) {
                    logi('启动成功');
                    result = true;
                    break;
                } else if (has(selectors)) {
                    let node = selectors.getOneNodeInfo(1000);
                    if (node) {
                        node.click()
                    }
                } else {
                    utils.openApp(packageName);
                    sleep(delay);
                    num++;
                }
            }
        }
    } else {
        loge('应用未安装');
    }
    if (result) {
        logd('应用版本号：' + utils.getAppVersionName(packageName));
    }
    return result;
};

/**
 * 自动激活
 * @param time
 * @returns {boolean|*}
 */
function autoServiceStart(time) {
    for (let i = 0; i < time; i++) {
        if (isServiceOk()) {
            return true;
        }
        let started = startEnv();
        logd("第" + (i + 1) + "次启动服务结果: " + started);
        if (isServiceOk()) {
            return true;
        }
    }
    return isServiceOk();
}

/**
 * 采集用户页笔记
 */
function collectUserNote(){
    initXHSNodeInfo(xhs_nodeInfo_path);
    let content = ["id搜索"];
    logd(content);
    let nick = id("com.xingin.xhs:id/cl7").getOneNodeInfo(1000).text;
    logd(nick);
    let xhsId = id("com.xingin.xhs:id/cl8").getOneNodeInfo(1000).text;
    xhsId = xhsId.split("：")[1];
    logd(xhsId);
    let width = device.getScreenWidth();
    let height = device.getScreenHeight();
    for (let i = 0; i < 9; i++) {
        rSwipe.rndSwipe(0.5*width,0.9*height,0.5*width,0.1*height,80,80,100);
        sleep(1000);
        clickPoint(0.25*width,0.5*height);
        sleep(3000);
        let isVideoNote = checkNoteType();
        logd("当前笔记是视频笔记："+isVideoNote);
        if (!isVideoNote) {
            rSwipe.rndSwipe(0.5*width,0.9*height,0.5*width,0.5*height,80,80,100);
            sleep(1000);
            let title = id("com.xingin.xhs:id/cb0").getOneNodeInfo(1000);
            if (title == null) {
                continue
            }
            title = title.text;
            content = content.concat(xhsId).concat(nick);
            content = content.concat(title).concat("点赞").concat("收藏");
            let t = content.join().replaceAll(",","----");
            file.appendLine(t,xhs_data_path);
            logd("写入成功");
            content = ["id搜索"];
            sleep(2000);
            picwordBack();
        }else {
            sleep(2000);
            let title = id("com.xingin.hs:id/noteContentText").getOneNodeInfo(1000);
            if (title == null) {
                continue
            }

            title = title.text;
            title = title.substring(0,title.indexOf("..."));
            content = content.concat(xhsId).concat(nick);
            content = content.concat(title).concat("点赞").concat("收藏");
            let t = content.join().replaceAll(",","----");
            file.appendLine(t,xhs_data_path);
            logd("写入成功");
            content = ["id搜索"];
            sleep(2000);
            videoBack();
        }
    }
}


/**
 * 采集关键字
 */
function collectKeyResult(key,type){
    initXHSNodeInfo(xhs_nodeInfo_path);
    let content = ["关键词"];
    clickText(type);
    sleep(5000);
    content = content.concat(key)
    let width = device.getScreenWidth();
    let height = device.getScreenHeight();
    for (let i = 0; i < 9; i++) {
        rSwipe.rndSwipe(0.5*width,0.9*height,0.5*width,0.1*height,80,80,100);
        sleep(1000);
        clickPoint(0.25*width,0.5*height);
        sleep(3000);
        let isVideoNote = checkNoteType();
        logd("当前笔记是视频笔记："+isVideoNote);
        if (!isVideoNote) {
            rSwipe.rndSwipe(0.5*width,0.9*height,0.5*width,0.5*height,80,80,100);
            sleep(1000);
            let title = id(enumId.picwordNote_title).getOneNodeInfo(1000);
            sleep(5000);
            logd(title);
            if (title == null) {
                picwordBack();
                continue
            }
            title = title.text;
            content = content.concat(title).concat(type).concat("点赞").concat("收藏");
            let t = content.join().replaceAll(",","----");
            file.appendLine(t,xhs_data_path);
            content = ["关键词",key];
            sleep(2000);
            picwordBack();
        }else {
            sleep(2000);
            let title = id(enumId.videoNote_title).getOneNodeInfo(1000);
            sleep(5000);
            logd(title);
            if (title == null) {
                picwordBack();
                continue
            }
            title = title.text;
            title = title.substring(0,title.indexOf("..."));
            content = content.concat(title).concat(type).concat("点赞").concat("收藏");
            let t = content.join().replaceAll(",","----");
            file.appendLine(t,xhs_data_path);
            logd("写入成功");
            content = ["关键词",key];
            sleep(2000);
            videoBack();
        }
    }

}


